package com.socialweb.web;

import com.socialweb.domain.UserData;
import com.socialweb.service.UserDataService;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class NavController {

    @Autowired
    private UserDataService userDataService;

    @RequestMapping(value = "/profile")
    public String profile(Model model) {
        model.addAttribute("user", userDataService.findById(1));
        return "profile";
    }

    @RequestMapping(value = "/")
    public String home() {
        return "redirect:/profile";
    }

    @RequestMapping(value = "/settings")
    public String settings(Model model) {
        model.addAttribute("user", userDataService.findById(1));
        return "settings";
    }

    @RequestMapping(value = "/changeSettings")
    public String changeSettings(Model model, @Valid final @ModelAttribute("user") UserData userData,
            final BindingResult result) {
        if (result.hasErrors()) {
            return "settings";
        } else {
            try {
                userDataService.updateAll(userData);
                model.addAttribute("user", userData);
                model.addAttribute("statusChange", "Changes are saved");
                return "settings";
            } catch (Exception e) {
                //как сообщить то, что изменеия не прошли?
                //а лучше всего вызвать метод, с своей моделью
                model.addAttribute("user", userDataService.findById(1));
                model.addAttribute("statusChange", "Change is not preserved. Try again.");
                return "settings";
            }
        }

    }
}
